<?php
/**
 * LeaveMsgModel.class.php
 * 留言模型
 * 
 * @author 	王中艺	<wangzy_smile@qq.com>
 * @date 	2017-05-10
 */

namespace Wechat\Model;

class LeaveMsgModel extends BaseModel {

	//重定义数据表
	protected 	$trueTableName 	= 't_leave_msg';

	/**
	 * 获取留言列表
	 * @param 	$relateType 	回复类型
	 * @param   $relateId 关联ID
	 * @param 	$showPlace 	展示位置
	 * @param 	$count 	加载条目数
	 * @return 	$list
	 */
	function getList($relateType, $relateId, $showPlace = false, $count = 100){
		$where 	= sprintf(
			'a.relate_type = %d and a.relate_id = %d and a.status = 1', 
			$relateType, $relateId
		);
		if($showPlace !== false && is_numeric($showPlace)){
			$where 	.= ' and a.show_place = '.$showPlace;
		}
		$list 	= $this->table('t_leave_msg a', null)
			->join('left join t_leave_msg b on b.relate_type = 9 and b.relate_id = a.id')
			->join('left join t_user c on a.user_id = c.id')
			->where($where)
			->order('id desc')
			->field('a.id, a.user_id, a.content, a.relate_type, a.create_time, a.status,
				b.id as res_id, b.user_id as res_user_id, b.content as res_content, 
				b.create_time as res_create_time, c.nickname, c.headimgurl')
			->cache(true)
			->select();

		$list 	= $this->_analyField('leaveMsg', $list, true);
		return $list;
	}

	/**
	 * 添加留言
	 * @param 	$userId 	用户ID
	 * @param 	$relateType 	留言类型
	 * @param 	$relateId 	关联ID
	 * @param 	$content 	留言内容
	 * @return 	boolean
	 */
	function addItem($userId, $relateType, $relateId, $content){
		$item 	= [
			'user_id' 	=> $userId,
			'relate_type' 	=> $relateType,
			'relate_id' 	=> $relateId,
			'content'	=> $content,
			'create_time'	=> time(),
			'update_time'	=> time(),
			'status' 	=> 0
		];

		$result 	= $this->add($item);
		if($result === false){
			$this->errMsg 	= '留言添加失败!';
			return false;
		}

		return true;
	}
}